package com.wcfsy.wechat.wx.um.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wcfsy.wechat.wx.exception.ServiceException;
import com.wcfsy.wechat.wx.um.entity.Permission;
import com.wcfsy.wechat.wx.um.entity.Role;
import com.wcfsy.wechat.wx.um.service.IPermissionService;
import com.wcfsy.wechat.wx.um.service.IRoleConService;
import com.wcfsy.wechat.wx.util.JsonMessage;

/**
 * 角色管理
 * 
 * @author yiqiang
 */
@Controller
@RequestMapping("/cms/role")
public class RoleController extends AbstractXssDefenderController {
	private static final Logger logger = LoggerFactory
			.getLogger(RoleController.class);
	@Resource
	private IPermissionService permissionService;
	@Resource
	private IRoleConService roleConService;

	@RequestMapping("/view/page")
	public ModelAndView pre_find() {
		ModelAndView mav = new ModelAndView("operator/manage_role");
		return mav;
	}

	@RequestMapping({ "/view" })
	@ResponseBody
	public Object find(Role param, int page, int rows) {
		/*
		 * User user = (User)
		 * SecurityManager.getSessionAttribute("SESSION_USER");
		 * 
		 * if ((param.getSource() != null) && (user.getSource() == Source.SF) &&
		 * (param.getSource().equals(Source.PAY))) { return new Page(new
		 * ArrayList(), 0L, page, rows); } if ((param.getSource() == null) &&
		 * (user.getSource() == Source.SF)) { param.setSource(user.getSource());
		 * } param.setOrgId(user.getRootOrgId());
		 */
		return this.roleConService.findRoleByPage(param, page, rows);
	}

	@RequestMapping({ "/modify/page" })
	public ModelAndView preModifyRole(int id) {
		ModelAndView mav = new ModelAndView("operator/modify_role");
		Role role = this.roleConService.getById(id);
		mav.addObject("role", role);
		return mav;
	}

	@RequestMapping({ "/modify" })
	@ResponseBody
	public JsonMessage modifyRole(Role role) {
		JsonMessage jsonMessage = new JsonMessage();
		/*
		 * try { CheckTokenUtils.checkTokenExists(); } catch (ServiceException
		 * e) { logger.error("Token为空。", e); jsonMessage.setSuccess("error");
		 * jsonMessage.setMessage("Token为空"); return jsonMessage; }
		 */
		// User user =
		// (User)SecurityManager.getSessionAttribute("SESSION_USER");
		try {
			role.setUpdateId(Long.valueOf(1));
			role.setUpdateDate(new Date());
			role.setCode(role.getCode());
			this.roleConService.update(role);
			jsonMessage.setSuccess("succeed");
			jsonMessage.setMessage("角色修改成功");
		} catch (ServiceException e) {
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("角色修改失败");
		}
		return jsonMessage;
	}

	@RequestMapping({ "/add/page" })
	public ModelAndView preAdd(Role role) {
		ModelAndView mav = new ModelAndView("operator/add_role");
		/*
		 * mav.addObject("systemMap", this.systemInfoService.queryAll());
		 * mav.addObject("source", Source.values()); mav.addObject("roleLevel",
		 * this._orgDataTypeService.queryByColumnName("ORG.TYPE_CODE"));
		 */
		return mav;
	}

	@RequestMapping({ "/auths/page/{id}" })
	public ModelAndView preAddPermis(@PathVariable("id") int roleId) {
		ModelAndView mav = new ModelAndView("operator/config_permission");

		List<Permission> permissionList = this.permissionService.findByParam(null);
		if (permissionList == null) {
			permissionList = new ArrayList<Permission>();
		}
		List<Permission>  myPermissionList = this.roleConService
				.getPermissionListByRoleId(roleId);
		if (myPermissionList == null) {
			myPermissionList = new ArrayList<Permission>();
		}
		mav.addObject("myPermissionList", myPermissionList);

		TreeMap<Long,Permission> map = new TreeMap<Long,Permission>();
		for (Permission p : permissionList) {
			p.setRemark("false");
			map.put(Long.valueOf(p.getId()), p);
		}

		for (Permission p1 : myPermissionList) {
			if (map.containsKey(Long.valueOf(p1.getId()))) {
				p1.setRemark("true");
				map.put(Long.valueOf(p1.getId()), p1);
			}
		}
		mav.addObject("permissionList", map);
		Role role = new Role();
		role = this.roleConService.getById(roleId);
		mav.addObject("role", role);
		return mav;
	}

	@RequestMapping({"/auths"})
	  @ResponseBody
	  public JsonMessage addPermis(HttpServletRequest request)
	  {
	    JsonMessage jsonMessage = new JsonMessage();
	    final int roleId = Integer.parseInt(request.getParameter("roleId"));
	    String permissions = request.getParameter("permissions");
	    logger.info("roleId={},permissions={}",roleId,permissions);
	    String[] permissionList = null;
	    if ((permissions != null) && (permissions.length() > 0)) {
	      permissionList = permissions.split(",");
	    }
	    final List<Long> permissionIdList = new ArrayList<Long>();
	    if ((null != permissionList) && (permissionList.length > 0)) {
	      for (int i = 0; i < permissionList.length; i++)
	        permissionIdList.add(Long.valueOf(permissionList[i]));
	    }
	    try
	    {
	      this.roleConService.configPermisList(roleId, permissionIdList);
	     /* new Thread(new Runnable( )
	      {
	        public void run() {
	          Role role = RoleController.this.roleConService.getById(roleId);
	          User user = (User)SecurityManager.getSessionAttribute("SESSION_USER");
	          List list = RoleController.this.roleConService.queryPerm(permissionIdList);
	          Map<String,String> param = new HashMap<String,String>();
	          param.put("操作员", user.getUserName());
	          param.put("角色名", role.getName());
	          param.put("权限", list == null ? "" : list.toString());
	          RoleController.this.roleConService.configPermisList(param);
	        }
	      }).start();*/
	      jsonMessage.setSuccess("succeed");
	      jsonMessage.setMessage("授权成功");
	    } catch (Exception e) {
	      logger.error("Error,when addPermis in RoleController!", e);
	      jsonMessage.setSuccess("error");
	      jsonMessage.setMessage("授权失败");
	    }
	    return jsonMessage;
	  }


}
